<?php

require_once ('DbUtils.php');
//require_once ("ip.php");


class PageUtils {
    public static function GetReuestParam($key) {
        $value = "";
        try {
            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key])) {
                $value = $_REQUEST[$key];
            }
        }
        catch(Exception $ex) {
            echo $ex->getMessage() . "<br>" . $ex->getTrace() . "<br>";
        }
        return $value;
    }

    public static function GetRequestParam($key) {
        $value = "";
        try {
            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key])) {
                $value = $_REQUEST[$key];
            }
        }
        catch(Exception $ex) {
            echo $ex->getMessage() . "<br>" . $ex->getTrace() . "<br>";
        }
        return $value;
    }


    public static function IsEmpty($value) {
        if($value==null || $value==""){
            return true;
        }
        return false;

    }

    public static function LoadBean($bean, $connection = null) {
        try {
            if ($bean != null) {
                $key = PageUtils::GetReuestParam($bean->_primarykey);
                if ($connection != null) {
                    $bean->connection = $connection;
                } else {
                    $bean->connection = DbUtils::pdo_connection();
                }
                if ($key != "") {
                    $bean->loadSelf($key);
                    if ($connection == null) {
                        //$bean->closeConnection();
                    }
                } else {
                    $bean->getcols();
                    $cols = array_keys($bean->_fields);
                    for ($i = 0; $i < count($cols); $i++) {
                        $key = $cols[$i];
                        $bean->set($key, null);
                    }
                }
            }
        }
        catch(Exception $ex) {
            echo $ex->getMessage() . "<br>" . $ex->getTrace() . "<br>";
        }
        return $bean;
    }
    
    
    

    public static function GenerateSessionID() {
        return trtoupper(md5(uniqid(mt_rand() , true)));
    }

    public static function FillBean($className = "",$bean = null) {
        
        if($bean==null && $className!=""){
        	  $bean = AbstractBean::LoadBean($className);
        }
        if($bean != null ){
      	    $keys = array_keys($_REQUEST);
		        $cols = $bean->getcols();
		        for ($i = 0; $i < count($keys); $i++) {
		            $key = $keys[$i];
		            if (array_key_exists($key, $cols)) {
		                $value = stripslashes($_REQUEST[$key]);
		                $bean->set($key, $value);
		            }
		        }
        }
      
        return $bean;
    }

		
		
    public static function DropDownList($className, $valueMember, $displayMemer, $selectValue = null, $filter = array() , $orderBy = "") {
        $strHtml = "";
        try {

            $bean = AbstractBean::LoadBean($className);
            $con = DbUtils::pdo_connection();
            if ($chartset != "") {
                $con->chartset = $chartset;
            }
            $bean->connection = $con;
            if ($orderBy=="" && $bean->_primarykey != null && $bean->_primarykey != "") {
                $orderBy = " order by " . $bean->_primarykey . " desc";
            }
            $rows = $bean->fetchArray($filter, $orderBy);
			
            for ($i = 0; $i < count($rows); $i++) {
                $row = (array)$rows[$i];
                $value = $row[$valueMember];
                $text = $row[$displayMemer];
                if ($value . "" == $selectValue . "") {
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $strHtml.= "<option " . $selected . " value=\"" . $value . "\">" . $text . "</option>";
                $bean->set($bean->_primarykey, $row[$bean->_primarykey]);
                $strHtml.= PageUtils::GetChildDropDownList($bean, $className, $valueMember, $displayMemer, $selectValue);
            }
        }
        catch(Exception $ex) {
            echo $ex->getTraceAsString();
        }
        return $strHtml;
    }

    private static function GetChildDropDownList($bean, $childName, $valueMember, $displayMemer, $selectValue = null, $_blank = "&nbsp;&nbsp;") {
        $strHtml = "";
        $chiledlist = $bean->loadChild($childName);
        for ($i = 0; $i < count($chiledlist); $i++) {
            $child = $chiledlist[$i];
            $child->connection = $bean->connection;
            $value = $child->get($valueMember);
            $text = $child->get($displayMemer);
            $selected = "";
            if ($value . "" == $selectValue . "") {
                $selected = "selected";
            }
            $strHtml.= "<option " . $selected . " value=\"" . $value . "\">" . $_blank . $text . "</option>";
            $strHtml.= PageUtils::GetChildDropDownList($child, $childName, $displayMemer, $selectValue, $_blank . "&nbsp;&nbsp;");
        }
        return $strHtml;
    }

    public static function get_contents($link) {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            $timeout = 0;
            curl_setopt($curl, CURLOPT_URL, $link);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_AUTOREFERER, true);
            $buffer = curl_exec($curl);
            curl_close($curl);
            return $buffer;
        } else if (function_exists('file_get_contents')) {
            $buffer = file_get_contents($link);
            return $buffer;
        } else if (function_exists('file')) {
            $buffer = implode('', @file($link));
            return $buffer;
        } else {
            return 0;
        }
    }

    public static function AlphaID($in, $to_num = false, $pad_up = false, $passKey = null) {
        $index = "0123456789abcdefghijklmnopqrstuvwyz";
        if ($passKey !== null) {
            for ($n = 0; $n < strlen($index); $n++) $i[] = substr($index, $n, 1);
            $passhash = hash('sha256', $passKey);
            $passhash = (strlen($passhash) < strlen($index)) ? hash('sha512', $passKey) : $passhash;
            for ($n = 0; $n < strlen($index); $n++) $p[] = substr($passhash, $n, 1);
            array_multisort($p, SORT_DESC, $i);
            $index = implode($i);
        }
        $base = strlen($index);
        if ($to_num) {
            $in = strrev($in);
            $out = 0;
            $len = strlen($in) - 1;
            for ($t = 0; $t <= $len; $t++) {
                $bcpow = bcpow($base, $len - $t);
                $out = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
            }
            if (is_numeric($pad_up)) {
                $pad_up--;
                if ($pad_up > 0) $out-= pow($base, $pad_up);
            }
            $out = sprintf('%F', $out);
            $out = substr($out, 0, strpos($out, '.'));
        } else {
            if (is_numeric($pad_up)) {
                $pad_up--;
                if ($pad_up > 0) $in+= pow($base, $pad_up);
            }
            $out = "";
            for ($t = floor(log($in, $base)); $t >= 0; $t--) {
                $bcp = bcpow($base, $t);
                $a = floor($in / $bcp) % $base;
                $out = $out . substr($index, $a, 1);
                $in = $in - ($a * $bcp);
            }
            $out = strrev($out); // reverse

        }
        return $out;
    }

	public function Sendemail($address,$displanName,$subject,$emailbody,$cc="")
	{
       // error_reporting(E_STRICT);
        //date_default_timezone_set("Asia/Shanghai");//设定时区东八区

        require_once('class.phpmailer.php');
        include("class.smtp.php");
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Host = "smtp.163.com";
        $mail->SMTPAuth = true;
        $mail->Username = "13917331474@163.com";
        $mail->Password ="zjomo2012";
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';

        $mail->From =$mail->Username;
        $mail->AddAddress($address,$address);

        $mail->IsHTML(true);
        $mail->Subject =$subject;
        $mail->Body = $emailbody;
        $mail->Send();

		/*	$mail = new PHPMailer(); //建立邮件发送类
			$mail->IsSMTP(); // 使用SMTP方式发送
			$mail->Host = "smtp.163.com";// 您的企业邮局域名
			$mail->SMTPAuth = true; // 启用SMTP验证功能
			$mail->Username = "13917331474@163.com"; // 邮局用户名(请填写完整的email地址)
			$mail->Password ="zjomo2012"; // 邮局密码

			$mail->CharSet = 'UTF-8';
			$mail->Encoding = 'base64';
			if($cc!=null && $cc!=""){
				$ccArray = explode(",","$cc");
				for($i=0;$i<count($ccArray);$i++){
					$mail->AddCC($ccArray[$i]);			
				}
			}
			$mail->From = "service@tuv.com"; //邮件发送者email地址
			$mail->FromName =$displanName;
			$mail->AddAddress($address,$address);//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
			$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
			$mail->Subject =$subject; //邮件标题
			$mail->Body = $emailbody; //邮件内容
         	$mail->Send();*/


	}
	
    public static function GetIPCity() {
        $ip = "Unknown";
        if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]) {
            $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        } else if ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"]) {
            $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
        } else if ($HTTP_SERVER_VARS["REMOTE_ADDR"]) {
            $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        } else if (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("REMOTE_ADDR")) {
            $ip = getenv("REMOTE_ADDR");
        }
        $city = iconv("gb2312", "utf-8", convertip($ip));
        if (strstr($city, "本机地址") != false) {
            $city = "上海";
        }
        return $city;
    }
	
	public static function getDistance($lat, $lng){ 
			$earthRadius = 6367000; //approximate radius of earth in meters 
			 /* 
			Convert these degrees to radians 
			to work with the formula 
			*/
			 
			$lat1 = ($lat * pi() ) / 180; 
			$lng1 = ($lng * pi() ) / 180; 
			
            $shopID = Users::GetLoginShopID();
			$shop = AbstractBean::LoadBean("Shop",$shopID);
            // print_r($shop);
			$lat2 = $shop->get("lat");
			$lng2 = $shop->get("lon");
			
			$lat2 = ($lat2 * pi() ) / 180; 
			$lng2 = ($lng2 * pi() ) / 180; 
			 
			$calcLongitude = $lng2 - $lng1; 
			$calcLatitude = $lat2 - $lat1; 
			$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
			$stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
			$calculatedDistance = $earthRadius * $stepTwo; 

			return round($calculatedDistance); 
	}
}
?>
